// app/src/main/java/com/example/snake/Snake.java
package com.example.snake;

import java.util.ArrayList;
import java.util.List;

public class Snake {
    private List<Point> body;
    private Direction direction;

    public Snake(int startX, int startY) {
        body = new ArrayList<>();
        body.add(new Point(startX, startY));
        direction = Direction.RIGHT;
    }

    public void move() {
        // 获取当前头部位置
        Point head = getHead();
        Point newHead = new Point(head.x, head.y);
        // 根据移动方向计算新的头部位置
        switch (direction) {
            case UP:
                newHead.y--;
                break;
            case DOWN:
                newHead.y++;
                break;
            case LEFT:
                newHead.x--;
                break;
            case RIGHT:
                newHead.x++;
                break;
        }
        // 将新头部添加到身体前端，并移除尾部节点实现移动
        body.add(0, newHead);
        body.remove(body.size() - 1);
    }

    public void grow() {
        Point tail = body.get(body.size() - 1);
        body.add(new Point(tail.x, tail.y));
    }

    public Point getHead() {
        return body.get(0);
    }

    public List<Point> getBody() {
        return body;
    }

    public Direction getDirection() {
        return direction;
    }

    public void setDirection(Direction direction) {
        this.direction = direction;
    }

    public static class Point {
        public int x, y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object obj) {
            // 检查对象类型是否为Point
            if (!(obj instanceof Point)) return false;
            Point other = (Point) obj;
            // 比较两个点的x和y坐标是否都相等
            return x == other.x && y == other.y;
        }
    }

    public enum Direction {
        UP, DOWN, LEFT, RIGHT
    }
}
